package cn.neusoft.neusoft_fz.controller;


import cn.neusoft.neusoft_fz.common.ResponseEntity;
import cn.neusoft.neusoft_fz.entity.DeliveryEntity;
import cn.neusoft.neusoft_fz.entity.InvoiceEntity;
import cn.neusoft.neusoft_fz.service.DeliveryOrderService;
import cn.neusoft.neusoft_fz.service.InvoiceProducer;
import cn.neusoft.neusoft_fz.service.InvoiceService;
import cn.neusoft.neusoft_fz.utils.PDFUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.example.entity.Invoice;
import org.example.entity.Payment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2023-06-25
 */
@Slf4j
@RestController
@RequestMapping("/invoice")
public class InvoiceController {

    @Autowired
    private InvoiceProducer invoiceProducer;

    @Autowired
    InvoiceService invoiceService;

    @Autowired
    DeliveryOrderService deliveryOrderService;


    @GetMapping("/all/{id}")
    public ResponseEntity<List<Invoice>> getBySubstationId(@PathVariable String id){

        List<Invoice> bySubstationId = invoiceService.getBySubstationId(id);
        return ResponseEntity.success(bySubstationId);
    }

    @GetMapping("/send/{str}")
    public ResponseEntity<String> sendtest(@PathVariable String str){

        invoiceProducer.sendToQueue(str);

        return ResponseEntity.success("成功发送");
    }

    @PostMapping("/create")
    public ResponseEntity create(@RequestBody Payment payment){
//        log.info(payment.toString());

        Gson gson = new Gson();

        LambdaQueryWrapper<Invoice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Invoice::getDeliveryOrderId,payment.getDeliveryOrderId());
        Invoice one = invoiceService.getOne(queryWrapper);
        if (one==null){

            Invoice invoice = new Invoice();
            invoice.setInvoiceAmount(payment.getPaymentAmount());
            invoice.setInvoiceStatus("未开票");
            invoice.setPaymentId(String.valueOf(payment.getPaymentId()));
            invoice.setDeliveryOrderId(payment.getDeliveryOrderId());

            invoiceService.save(invoice);

            String jsonStr = gson.toJson(invoice);
            log.info(jsonStr);
            invoiceProducer.sendToQueue(jsonStr);

            ResponseEntity<String> success = ResponseEntity.success(null);
            success.setMsg("成功申请发票信息");
            success.setCode(1);
            return success;
        }else {
            ResponseEntity<String> error = ResponseEntity.error(null);
            error.setMsg("无需重复申请");
            error.setCode(0);
            return error;
        }
    }

    @PostMapping(path = "/createPdf", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_PDF_VALUE)
    public byte[] createPdf(@RequestBody InvoiceEntity data) throws Exception {


        log.info(data.toString());

        // Create a unique temporary file
        File tempFile = File.createTempFile("invoice-", ".pdf");
        String dest = tempFile.getAbsolutePath();



        new PDFUtils().createInvoicePdf(dest, data);

        // Ensure the file has been fully written
        byte[] pdfBytes = null;
        if (Files.exists(Paths.get(dest))) {
            pdfBytes = Files.readAllBytes(Paths.get(dest));
            log.info("PDF file read successfully. Size: " + pdfBytes.length + " bytes");

            // Ensure the file has been fully read before deleting
            Files.delete(Paths.get(dest));
            log.info("Temp file deleted successfully.");
        } else {
            log.error("Failed to create PDF, temp file does not exist.");
        }

        return pdfBytes;
    }

}
